package com.mysteel.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ProjectName: mail
 * ClassName: FeignConfig
 * Description:
 * date: 2021/04/06/006 10:00
 *
 * @author xiaochao
 */
@Configuration
public class FeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            /**
             * @param template:feign包装的新的请求，用于调用远程接口
             */
            @Override
            public void apply(RequestTemplate template) {
                // 获取浏览器发过来的原生请求，请求信息放在threadLocal中，异步调用的时候会出问题，threadLocal线程隔离，数据不共享
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes == null){
                    return;
                }
                HttpServletRequest request = requestAttributes.getRequest();
                // 同步请求头数据，cookie
                String cookie = request.getHeader("Cookie");
                // 将原生请求中的cookie请求头放到feign新建的请求中
                template.header("Cookie",cookie);
            }
        };
    }
}
